/*
 [The "BSD license"]
 Copyright (c) 2011-2011 Joel Li (李家智)
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
 3. The name of the author may not be used to endorse or promote products
     derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.bee.tl.core;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.logging.Logger;

import org.bee.tl.core.compile.CompiledClass;
import org.bee.tl.core.compile.PreCompileException;
import org.bee.tl.core.io.ByteWriter;

public class CompiledBeeTemplate extends AbstractTemplate
{

	CompiledClass cls = null;
	String child = null;
	static Logger logger = Logger.getLogger(CompiledBeeTemplate.class.toString());

	public CompiledBeeTemplate(String child, GroupTemplate group)
	{
		this.child = child;
		this.setGroupTemplate(group);
		cls = group.classMap.getClass(child);
		if (cls != null)
		{
			Resource resource = new Resource(new File(group.root.toString(), child), group.charset, group.root);
			resource.setCR(cls.getCR());
			cls.setResource(resource);
		}

	}

	public void getText(Writer pw) throws IOException, BeeException
	{
		if (directByteOutput && !(pw instanceof ByteWriter))
		{

			throw new IllegalStateException("二进制输出，因此输出流不能是Writer");
		}
		if (pw instanceof ByteWriter)
		{
			this.getTextByByteWriter((ByteWriter) pw);
		}
		else
		{
			this.getTextByByteWriter(new ByteWriter(pw));
		}
	}

	public void getTextByByteWriter(ByteWriter pw) throws IOException, BeeException
	{

		// 没有编译，或者模板文件已经被更新
		if (cls == null)
		{
			runAsPreCompiledClass(pw, child);
			return;
		}

		try
		{
			cls.setTemplate(this);
			cls.service(pw, this.context);
		}
		catch (PreCompileException ex)
		{
			// cast exception
			logger.info("优化失败:" + child + ",原因是" + ex.getMessage());
			delete();
			runAsErrorPreCompiledClass(pw, child);
		}
		catch (BeeException ex)
		{
			if (cls.getResource() == null)
			{
				Resource resource = new Resource(new File(group.root.toString(), child), group.charset);
				resource.setCR(cls.getCR());
				cls.setResource(resource);
				ex.setResource(resource);

			}
			else
			{
				ex.setResource(cls.getResource());
			}
			if (this.group.errorHandler != null)
			{
				this.group.errorHandler.processExcption(ex);
			}
			else
			{
				throw ex;
			}
		}

		catch (Error ex)
		{
			if (ex.getMessage() != null || ex.getMessage().indexOf("Unresolved compilation problem:") != -1)
			{
				// 不能正确运行，某些类已经改变,重新优化
				delete();
				runAsPreCompiledClass(pw, child);
			}
			else
			{
				throw ex;
			}

		}
	}

	private void runAsPreCompiledClass(ByteWriter pw, String key) throws IOException, BeeException
	{
		try
		{
			cls = new PreCompiledClass();
			cls.setTemplate(this);
			((PreCompiledClass) cls).setBeeTemplate(group, child);
			group.classMap.setClass(key, cls);
			cls.service(pw, this.context);
		}

		catch (BeeException ex)
		{
			if (cls.getResource() == null)
			{
				Resource resource = new Resource(new File(group.root.toString(), child), group.charset);
				resource.setCR(cls.getCR());
				ex.setResource(resource);

			}
			else
			{
				ex.setResource(cls.getResource());
			}
			if (this.group.errorHandler != null)
			{
				this.group.errorHandler.processExcption(ex);
			}
			else
			{
				throw ex;
			}

		}

	}

	private void runAsErrorPreCompiledClass(ByteWriter pw, String key) throws IOException, BeeException
	{
		try
		{
			cls = new PreCompiledClass();
			cls.setCompileError(true);
			cls.setTemplate(this);
			((PreCompiledClass) cls).setBeeTemplate(group, child);
			group.classMap.setClass(key, cls);

			cls.service(pw, this.context);
		}
		catch (BeeException ex)
		{

			ex.setResource(cls.getResource());
			if (this.group.errorHandler != null)
			{
				this.group.errorHandler.processExcption(ex);
			}
			else
			{
				throw ex;
			}
		}

	}

	private void delete()
	{

		String[] strs = BeetlUtil.getPackage2Class(this.child);
		String classFile = strs[0].replace('.', File.pathSeparatorChar) + File.separator + strs[1];
		File f = new File(group.getTargetClassPath() + File.separator + classFile + ".class");
		if (!f.delete())
		{
			// bug ,can not delete ,why?
			System.out.println("can not delete file " + f.toString());
		}
	}

	@Override
	public String getCR()
	{
		return cls.getCR();
	}

}
